package com.example.dynamicdatasource.aspect;

import com.example.dynamicdatasource.annotation.DataSource;
import com.example.dynamicdatasource.dataSource.DynamicDataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author mqb
 * @date 2021/8/9 20:05
 */
@Aspect
@Component
@Slf4j
public class DynamicDataSourceAspect {

    @Pointcut("@within(com.example.dynamicdatasource.annotation.DataSource)||@annotation(com.example.dynamicdatasource.annotation.DataSource)")
    public void pt() {
    }

    @Before("pt()")
    public void before(JoinPoint jp) {
        String key = getRoutingKey(jp);
        DynamicDataSourceHolder.set(key);
        log.info("set current datasource: {}", key);
    }

    private String getRoutingKey(JoinPoint jp) {
        // 获取方法上的 @DataSource注解
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        DataSource annoOnMethod = methodSignature.getMethod().getAnnotation(DataSource.class);
        if (annoOnMethod == null) {
            Class<?> clazz = jp.getTarget().getClass();
            DataSource annoOnClazz = clazz.getAnnotation(DataSource.class);
            return annoOnClazz.value();
        }
        return annoOnMethod.value();
    }
}
